package com.springboot.demo.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.cx.item.common.exception.CommonException;
import com.cx.item.common.utils.StringUtil;
import com.cx.item.common.utils.TokenUtil;
import com.springboot.demo.mapper.ManagerMapper;
import com.springboot.demo.model.example.ManagerExample;
import com.springboot.demo.model.model.Manager;
import com.springboot.demo.service.UserPassPortService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by hevin on 2017/11/6.
 */
@Service
public class UserPassPortServiceImpl implements UserPassPortService {

    @Autowired
    private ManagerMapper managerMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public String login(String loginname, String pwdstr, String tokenTimeOutStr) {
        String tokenStr = null;

        ManagerExample example = new ManagerExample();
        ManagerExample.Criteria criteria = example.createCriteria();
        criteria.andLoginNameEqualTo(loginname);
        criteria.andLoginPwdEqualTo(pwdstr);
        List<Manager> managerList = managerMapper.selectByExample(example);
        if (CollUtil.isNotEmpty(managerList)) {
            Manager manager = managerList.get(0);
            Integer lgoinStatus = manager.getIsActivate();
            if (1 != lgoinStatus) {
                throw new CommonException("此账号被禁用");
            }

            //正常用户  成功登陆
            //登陆成功，需要生产token 发给前端  并更新数据库
            tokenStr = TokenUtil.generateToken(manager.getManagerId().toString(), StringUtil.getStringRandom(6));
            String tokenStrVal = tokenStr + ":" + manager.getManagerId();
            //更新redis中的token
            redisTemplate.opsForValue().set(tokenStr, tokenStrVal, Long.parseLong(tokenTimeOutStr), TimeUnit.MINUTES);
            String tokenStrOld = manager.getTokenStr();
            if (!StringUtils.isEmpty(tokenStrOld)) {
                redisTemplate.delete(tokenStrOld);
            }

            Manager managerUpd = new Manager();
            managerUpd.setManagerId(manager.getManagerId());
            managerUpd.setTokenStr(tokenStr);
            managerMapper.updateByPrimaryKeySelective(managerUpd);

        } else {
            throw new CommonException("账号或者密码错误");
        }

        return tokenStr;
    }


}
